import { Component } from 'react'
import { Button, Form, Input, Select } from 'antd'
import { FormComponentProps } from 'antd/lib/form'
import { capitalize } from 'lodash'
import { User } from '../type'

interface Props {
  data: User
  editing: boolean
  onSubmit: (x: Partial<User>) => void
  onEdit: () => void
  onDelete: () => void
  onCancel: () => void
}

@(Form.create as any)()
class UserForm extends Component<Props & FormComponentProps> {
  layout = {
    labelCol: { span: 8 },
    wrapperCol: { span: 8 },
  }

  handleSubmit = (event: React.FormEvent<never>) => {
    event.preventDefault()
    const {
      data: { id },
      onSubmit,
      form,
    } = this.props
    form.validateFieldsAndScroll(
      (error: Error, values: Record<keyof User, string>) =>
        !error &&
        onSubmit({
          id,
          username: values.username.trim(),
          name: (values.name || '').trim(),
          role: values.role,
        }),
    )
  }

  render() {
    return (({ data, editing, onEdit, onDelete, onCancel, form }) => (
      <Form onSubmit={this.handleSubmit}>
        <Form.Item {...this.layout} label="Username">
          {form.getFieldDecorator('username', {
            initialValue: data.username,
            rules: [
              {
                required: true,
                whitespace: true,
                message: 'Please input the username',
              },
            ],
          })(<Input disabled={!editing} />)}
        </Form.Item>
        <Form.Item {...this.layout} label="Nickname">
          {form.getFieldDecorator('name', {
            initialValue: data.name,
          })(<Input disabled={!editing} />)}
        </Form.Item>
        <Form.Item {...this.layout} label="Role">
          {form.getFieldDecorator('role', {
            initialValue: data.role,
            rules: [
              {
                required: true,
                message: 'Please input the role',
              },
            ],
          })(
            <Select disabled={!editing}>
              {ROLES.map(x => (
                <Select.Option key={x} value={x}>
                  {capitalize(x)}
                </Select.Option>
              ))}
            </Select>,
          )}
        </Form.Item>
        <Form.Item wrapperCol={{ offset: this.layout.labelCol.span }}>
          {!editing ? (
            <Button onClick={onEdit}>Edit</Button>
          ) : !data.id ? (
            <Button htmlType="submit">Create</Button>
          ) : (
            <div>
              <Button htmlType="submit">Update</Button>
              <span style={{ margin: '12px' }} />
              <Button onClick={onDelete}>Delete</Button>
              <span style={{ margin: '12px' }} />
              <Button onClick={onCancel}>Cancel</Button>
            </div>
          )}
        </Form.Item>
      </Form>
    ))(this.props)
  }
}

const ROLES = ['CUSTOMER', 'MANAGER', 'ADMINISTRATOR']

export default (UserForm as any) as React.ComponentClass<Props>
